package cn.duhengkui.national.valuelist.core.data.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import cn.duhengkui.national.valuelist.core.entity.SqlAndParams;

/**   
 * <table border="1">
 *	<tr><td>包名称：</td><td>com.zhibo.tientsin.transmission.tower.lot.utils.valuelist</td></tr>
 *	<tr><td>类名称：</td><td>SimpleStatementBuilder</td></tr>
 *	<tr><td>类描述：</td><td></td></tr>
 *	<tr><td>创建人：</td><td>杜恒奎</td></tr>
 *  <tr><td>创建时间：</td><td>2016年7月9日/下午5:02:12</td></tr> 
 *  <tr><td>版本：</td><td>1.0.0</td></tr>
 * </table>   
 *     
 */
public class SimpleStatementBuilder {
	
	private static final String PARAM_START_MARK = "#{";
	private static final String PARAM_END_MARK = "}";
	
	private static List<TextManipulator> textManipulators = new ArrayList<TextManipulator>();
	

	public static SqlAndParams generate(StringBuilder query,Map<String, Object> whereClause)
	{
		if (whereClause == null) {
			whereClause = Collections.emptyMap();
		}
		if(textManipulators.size() == 0){
			textManipulators.add(new FilterTextManipulator());
			textManipulators.add(new TokenReplaceTextManipulator());
		}
		for (Iterator<TextManipulator> iter = textManipulators.iterator(); iter.hasNext();) {
			TextManipulator manipulator = (TextManipulator) iter.next();
			manipulator.manipulate(query, whereClause);
		}
		LinkedList<Object> arguments = new LinkedList<Object>();
		for (int end = 0, start; ((start = query.toString().indexOf(PARAM_START_MARK,end)) >= 0);) {
			end = query.toString().indexOf(PARAM_END_MARK, start);
			String key = query.substring(start + PARAM_START_MARK.length(), end);
			Object value;
			try {
				value = ReflectUtil.getValue(whereClause, key);
			} catch (Exception e) {
				throw new NullPointerException("Property '" + key
						+ "' was not provided.");
			}
			if (value == null) {
				throw new NullPointerException("Property '" + key
						+ "' was not provided.");
			}
			if(value.getClass().isArray()){
				Integer replyLength = 1;
				Object[] arrayValue = (Object[])value;
				replyLength = arrayValue.length;
				String replays = "";
				for(int i = 0; i < replyLength; i++){
					arguments.add(arrayValue[i]);
					replays +="?,";
				}
				if(replays.length() > 0){
					replays = replays.substring(0, replays.length() - 1);
				}
				query.replace(start, end + PARAM_END_MARK.length(), replays);
			}else{
				arguments.add(value);
				query.replace(start, end + PARAM_END_MARK.length(), "?");
			}
			end -= (key.length() + PARAM_START_MARK.length());
		}
		SqlAndParams result = new SqlAndParams();
		result.setSql(query.toString());
		result.setParams(arguments);
		return result;
	}
	

}
